package com.ictravi.iamunit.connector;

import java.util.Collection;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.ictravi.iamunit.IAMUnitException;
import com.ictravi.iamunit.IAMUnitTestCase;

/**
 * HTTPConnector to allow for testing to/from Webistes
 * 
 * @author Albert Louw (alouw@ictavi.com)
 * @version v1.0.0
 **/
public class HTTPConnector extends AbstractConnector {
	private static Log LOG = LogFactory.getLog(IAMUnitTestCase.class);
	private Map<String, String> config;

	/**
	 * setup for HTTPConnector
	 * 
	 * @since v1.0.0
	 * @param config
	 *            configuration setting
	 * @throws IAMUnitException
	 * @throws NoSuchAlgorithmException 
	 * @throws IOException 
	 * @throws IllegalStateException 
	 **/
	public void setup(Map<String, String> config) throws IAMUnitException
	{
		this.config = config;
		LOG.debug("...in: HTTPConnector - setup");
	}

	/**
	 * inserts a row in database with values from sheet
	 * @param dataRow
	 * 			Row with data from testsheet
	 * @since v1.0.0
	 * @throws IAMUnitException
	 **/
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void opGetWeb(Map<String, Collection<String>> dataRow) throws IAMUnitException {
		LOG.debug("...in: HTTPConnector: opGetWeb");
		String str = config.get("class");
		String meth= "";
		for (String name : dataRow.keySet()) {
			if (name.equalsIgnoreCase("dn"))
			{
				meth = dataRow.get(name).toString().replace("[", "");
				meth = meth.replace("]", "");
				LOG.debug("...method: " + meth);
			}
			else
				throw new IAMUnitException("... no method specified.");
		}
		try {
			Class cl=Class.forName(str);
			Method mthd=cl.getMethod(meth);
			mthd.invoke(Class.forName(str));
		} catch (IllegalAccessException e) {
			throw new IAMUnitException("... HTTP error IAE: " + e.getMessage());
		} catch (ClassNotFoundException e) {
			throw new IAMUnitException("... HTTP error: CNF  " + e.getMessage());
		} catch (SecurityException e) {
			throw new IAMUnitException("... HTTP error: SE   " + e.getMessage());
		} catch (NoSuchMethodException e) {
			throw new IAMUnitException("... HTTP error: NSM  " + e.getMessage());
		} catch (IllegalArgumentException e) {
			throw new IAMUnitException("... HTTP error: IAE  2" + e.getMessage());
		} catch (InvocationTargetException e) {
			throw new IAMUnitException("... HTTP error: ITE  " + e.getMessage());
		}
	}
	
	/**
	 * tears down connection
	 * 
	 * @since v1.0.0
	 * @throws IAMUnitException
	 **/
	public void tearDown() throws IAMUnitException {
		LOG.debug("...in HTTPConnector - teardown");
	}
}
